package com.orangelife.service.base.dict.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.orangelife.service.base.dict.Dictionary;

public abstract class AbstractDictionary<K, T> implements Dictionary<K, T> {

	private Map<K, T> dictMap = new HashMap<K, T>();

	public T get(K key) {
		if (key == null)
			return null;
		return dictMap.get(key);
	}

	public boolean isEmpty() {
		return dictMap.isEmpty();
	}

	public Set<K> keys() {
		return dictMap.keySet();
	}

	public int size() {
		return dictMap.size();
	}

	@SuppressWarnings("unchecked")
	public Dictionary<K, T> clone() {
		AbstractDictionary<K, T> dictionary = null;
		try {
			dictionary = (AbstractDictionary<K, T>) super.clone();
		} catch (CloneNotSupportedException e) {
			return null;
		}
		dictionary.dictMap = new HashMap<K, T>();
		for (K key : dictMap.keySet()) {
			dictionary.dictMap.put(key, dictMap.get(key));
		}
		return dictionary;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<K> keysList(Comparator<K> comparator) {
		List tmpList = new ArrayList(dictMap.keySet());
		if (comparator != null) {
			Collections.sort(tmpList, comparator);
		} else {
			Collections.sort(tmpList);
		}
		return tmpList;
	}

	protected void setDictMap(Map<K, T> dictMap) {
		synchronized (this.dictMap) {
			for (K key : dictMap.keySet()) {
				if (key == null)
					continue;
				this.dictMap.put(key, dictMap.get(key));
			}
		}
	}

	protected void addDictEntry(K key, T value) {
		synchronized (dictMap) {
			dictMap.put(key, value);
		}
	}

	public void toMaps(Map<K, T> container) {
		for (K key : keys()) {
			container.put(key, get(key));
		}
	}

}
